import threading
import redis
from database import cache
class PSListener(threading.Thread):
    def __init__(self, channels):
        threading.Thread.__init__(self)
        self.redis = cache()._re_server.re_sv
        self.pubsub = self.redis.pubsub()
        self.pubsub.subscribe(channels)
#------------------------------------------------------------------------------ 
    def work(self, item):
        print item['channel'], ":", item['data']
#------------------------------------------------------------------------------ 
    def run(self):
        for item in self.pubsub.listen():
            if item['data'] == "KILL":
                self.pubsub.unsubscribe()
                print self, "unsubscribed and finished"
                break
            else:
                self.work(item)
#------------------------------------------------------------------------------ 
if __name__ == "__main__":
    r = redis.Redis()
    client = PSListener(r, ['test'])
    client.start()
    
    r.publish('test', 'sak')
    r.publish('test', 'this will reach the listener')
    r.publish('fail', 'this will not')
    
    r.publish('test', 'KILL')